package com.example.rabbitmq.starter.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ配置类
 */
@Configuration
public class RabbitMQConfig {

    @Resource
    private ConnectionFactory connectionFactory;




    /**
     * 配置消息转换器
     */
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 配置RabbitAdmin
     */
    @Bean
    public RabbitAdmin rabbitAdmin() {
        return new RabbitAdmin(connectionFactory);
    }

    /**
     * 配置RabbitTemplate（使用Spring Boot自动配置的RabbitTemplate）
     */
    @Bean
    @Primary
    public RabbitTemplate configureRabbitTemplate(RabbitTemplate rabbitTemplate) {
        // 消息转换器
        rabbitTemplate.setMessageConverter(jsonMessageConverter());

        // 开启消息确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                System.out.println("消息发送失败：" + cause + ", correlationData: " + correlationData);
                // TODO: 处理消息发送失败的情况，可以记录日志、保存消息等
            }
        });

        // 开启消息返回回调
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("消息被退回：" + new String(message.getBody()) + ", replyCode: " + replyCode
                    + ", replyText: " + replyText + ", exchange: " + exchange + ", routingKey: " + routingKey);
            // TODO: 处理消息被退回的情况
        });

        return rabbitTemplate;
    }


}